package anly;


import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class PortScaner {
    public static void main(String[] args) throws InterruptedException {
        String host = "172.168.4.105";
        int startPort =1;
        int endPort = 36000;
        int step =  Math.round(endPort/500)+1;

        for(int i=1;i<step;i++){
            int start = startPort+(i-1)*500;
            int end = startPort+i*500;
            System.out.println("正在扫描"+start+"-"+end);
            SP(host,start,end);
        }
    }
    public static void SP(String host,int startPort,int endPort) throws InterruptedException {
        List<Integer> portList = new ArrayList<>();
        final CountDownLatch latch = new CountDownLatch(endPort-startPort+1);
        for (int port = startPort; port <= endPort; port++) {
            int finalPort = port;
            //System.out.println(port);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    Socket socket = new Socket();
                    try {
                        socket.connect(new InetSocketAddress(host, finalPort));
                        System.out.println("端口" + finalPort + "开放");
                        portList.add(finalPort);
                    } catch (Exception e) {
                        //e.printStackTrace();
                        // System.out.println("端口" + finalPort + "未开放");
                    }
                    latch.countDown();
                }
            });
            thread.start();
        }
        latch.await();
        portList.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }
        });
    }
}